<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <style>
      * {
          box-sizing: border-box;
          margin: 0;
      }

      #scrollArea {
          width: 400px;
          height: 400px;
          border: 1px solid darkslategray;
          overflow: auto;
      }

      .box {
          width: 200px;
          height: 200px;
          border: 1px solid gray;
      }
  </style>
</head>
<body>
<div id="scrollArea">
  <div class="box">box</div>
  <div class="box">box</div>
  <div id="targetBox" class="box">box</div>
</div>
<script>
  window.onload = () => {
    const scrollAreaEle = document.getElementById('scrollArea')
    const targetEle = document.getElementById('targetBox')
    const observer = new IntersectionObserver((entries) => {
      entries.forEach(entry => {
        console.log('entry:', entry)
        if (entry.intersectionRatio >= 0.5) {
          // 使 IntersectionObserver 对象停止监听
          // observer.disconnect()

          // 使IntersectionObserver停止监听特定目标元素。
          // observer.unobserve(targetEle)

          // 返回所有观察目标的IntersectionObserverEntry对象数组
          // console.log('takeRecords:',observer.takeRecords())
        }
      })
    }, {
      root: scrollAreaEle, // 指定根元素，不指定或null是将默认为浏览器视窗
      // rootMargin: '100px', // 该属性可以控制root元素每一边的收缩或者扩张。默认值为'0px'
      threshold: [0, 0.25, 0.5, 0.75, 1.0]  // Number / Number[] target元素和root元素相交程度达到该值的时候IntersectionObserver注册的回调函数将会被执行
    })

    // 监听目标元素
    observer.observe(targetEle)
    console.log("observer:",observer)
  }
</script>
</body>
</html>
